package com.dexilaonian.fragment;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.dexilaonian.MainActivity;
import com.dexilaonian.R;
import com.dexilaonian.activity.LoginActivity;
import com.dexilaonian.activity.SearchActivity;
import com.dexilaonian.activity.ShoppingTrolleyActivity;
import com.dexilaonian.adpter.ContentAdapter;
import com.dexilaonian.adpter.TitleAdapter;
import com.dexilaonian.bean.ContentBean;
import com.dexilaonian.bean.StoreBean;
import com.dexilaonian.ui.BaseFragment;
import com.dexilaonian.utils.Constant;
import com.dexilaonian.utils.JsonUtil;
import com.dexilaonian.utils.Okhttp;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

public class StoreFragment extends BaseFragment {
    private static int COUNT = 0;
    public static int POSITION = 0;
    @Bind(R.id.et_sousu_text)
    EditText etSousuText;
    @Bind(R.id.iv_store_search)
    ImageView ivStoreSearch;
    @Bind(R.id.tv_store_search)
    TextView tvStoreSearch;
    @Bind(R.id.trolley_num)
    TextView trolleyNum;
    @Bind(R.id.listview_title)
    ListView listviewTitle;
    @Bind(R.id.listview_content)
    ListView listviewContent;


    private List<StoreBean> titleList = new ArrayList<>();
    private List<ContentBean> contextList = new ArrayList<>();
    private Map<String, String> contentMap = new HashMap<>();
    private TitleAdapter storeAdapter;
    private int categoryid = 0;
    private String content_url;
    private ContentAdapter contentAdapter;
    private List<StoreBean> storeBeen;
    private boolean FLAG = true;
    private FragmentActivity mContext;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (mContext == null) {
            mContext = getActivity();
        }

    }
    @Override
    protected void initData(Bundle savedInstanceState) {

    }

    @Override
    protected void initView(View layoutView) {
    }

    @Override
    public int getLayoutID() {
        return R.layout.fragment_store;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        ButterKnife.bind(this, rootView);
        initTitle();
        return rootView;
    }

    @Override
    public void onResume() {
        super.onResume();
        initGetCartNum();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }
    private void initGetCartNum() {
        String cartNum_url = Constant.base_url + "/cart/count.do";
        Map<String, String> cartNum_map = new HashMap<>();
        Okhttp.postString(true, cartNum_url, cartNum_map, new Okhttp.CallBac() {
            @Override
            public void onError(Call call, Exception e, String state, int id) {
                showToast(state);
            }

            @Override
            public void onResponse(String response, int id) {

                try {
                    JSONObject jsonObject = new JSONObject(response);
                    int status = Integer.parseInt(jsonObject.optString("status"));
                    if (status == 0) {
                        int data = Integer.parseInt(jsonObject.optString("data"));
                        if (trolleyNum != null) {
                            trolleyNum.setText(data + "");
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onNoNetwork(String state) {
                showToast(state);
            }
        });
    }

    private void initTitle() {
        String categoryId_url = Constant.base_url + "/product/getCategorysOfShop";
        etSousuText.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                startActivity(new Intent(mContext, SearchActivity.class));
                return true;
            }
        });
        if (titleList != null) {
            titleList.clear();
        }
        if (contextList != null) {
            contextList.clear();
        }
        Map<String, String> categoryId_map = new HashMap<>();
        Okhttp.postString(false, categoryId_url, categoryId_map, new Okhttp.CallBac() {
            @Override
            public void onError(Call call, Exception e, String state, int id) {
                showToast(state);
            }

            @Override
            public void onResponse(String response, int id) {
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    int status = Integer.parseInt(jsonObject.optString("status"));
                    if (status == 34 || status == 16) {
                        startActivity(new Intent(mContext, LoginActivity.class));
                        return;
                    }
                    String data = jsonObject.optString("data");
                    storeBeen = JsonUtil.json2beans(data, StoreBean.class);
                    int id0 = storeBeen.get(0).getId();
                    getContent(id0);
                    titleList.clear();
                    titleList.addAll(storeBeen);
                    storeAdapter = new TitleAdapter(mContext, titleList);
                    listviewTitle.setAdapter(storeAdapter);

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onNoNetwork(String state) {
                showToast(state);
            }
        });
        content_url = Constant.base_url + "/product/getProductsOfShopByCategoryID";
        //getContent(0);
  /*      listviewContent.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {

            }
            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                if (firstVisibleItem != POSITION) {
                    POSITION = firstVisibleItem;
                    storeAdapter.notifyDataSetChanged();
                }
            }
        });*/
        listviewTitle.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                POSITION = position;
                int id1 = storeBeen.get(position).getId();
                getContent(id1);
                storeAdapter.notifyDataSetChanged();
                contentAdapter.notifyDataSetChanged();
                listviewContent.setSelection(position);
                listviewContent.smoothScrollToPositionFromTop(position, 0, 100);
            }
        });
    }

    private void getContent(int i) {
        contentMap.put("categoryid", i + "");
        contentMap.put("index", 1 + "");
        contentMap.put("pageSize", 10 + "");
        Okhttp.postString(false, content_url, contentMap, new Okhttp.CallBac() {
            @Override
            public void onError(Call call, Exception e, String state, int id) {
            }

            @Override
            public void onResponse(String response, int id) {
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    int status = Integer.parseInt(jsonObject.optString("status"));
                    if (status == 34 || status == 16) {
                        startActivity(new Intent(mContext, LoginActivity.class));
                        return;
                    }
                    String data = jsonObject.optString("data");
                    JSONObject object = new JSONObject(data);
                    String items = object.optString("items");
                    List<ContentBean> contentBeen = JsonUtil.json2beans(items, ContentBean.class);

                    contextList.clear();
                    contextList.addAll(contentBeen);
                    contentAdapter = new ContentAdapter(mContext, contextList);
                    listviewContent.setAdapter(contentAdapter);

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onNoNetwork(String state) {

            }
        });
        final ContentAdapter contentAdapter = new ContentAdapter(mContext, contextList);
        listviewContent.setAdapter(contentAdapter);
        contentAdapter.notifyDataSetChanged();
    }

    @OnClick({R.id.iv_store_search, R.id.tv_store_search})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_store_search:
                Intent intent = new Intent(mContext, ShoppingTrolleyActivity.class);
                startActivity(intent);
                break;
        }
    }
}
